package com.boot.security.config.handler;

import com.boot.web.exception.ModuleExceptionHandler;
import com.boot.web.http.HttpModel;
import com.boot.web.util.HttpResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 为 {@link AccessDeniedException} 进行错误处理
 * @date 2020/2/16 15:51
 **/
@Component
@Slf4j
public class AccessExceptionHandler implements AccessDeniedHandler, ModuleExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String uri = request.getRequestURI();
        log.warn("拒绝用户访问 uri：{} ,错误信息：{}", uri, accessDeniedException.getMessage());
        HttpResponseUtil.writeResponse(response, HttpResponseUtil.forbidden(accessDeniedException.getMessage()));
    }

    @Override
    public boolean support(Exception e) {
        return e instanceof AccessDeniedException;
    }

    @Override
    public int order() {
        return 30;
    }

    @Override
    public ResponseEntity<HttpModel<Object>> handle(Exception e) {
        return HttpResponseUtil.forbidden(e.getMessage());
    }
}
